package com.quanta.edaily.controller;

import com.quanta.edaily.Service.ArticleService;
import com.quanta.edaily.bean.JsonResponse;
import com.quanta.edaily.bean.contants.ResultCode;
import com.quanta.edaily.pojo.Article;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Min;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
@Validated
public class ArticleController {
    @Resource
    ArticleService articleService;

    @PostMapping("/insert")
    public JsonResponse insert(@RequestBody Article article) {
        if (articleService.insert(article) == 1) return JsonResponse.success("插入成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "插入失败");
    }

    @PostMapping("/deleteById/{id}")
    public JsonResponse deleteById(@PathVariable Integer id) {
        if (articleService.deleteById(id) == 1) return JsonResponse.success("删除成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "删除失败");
    }

    @PostMapping("/updateById")
    public JsonResponse updateById(@RequestBody Article article) {
        if (articleService.updateById(article) == 1) return JsonResponse.success("更改成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "更改失败");
    }

    @GetMapping("/getById/{id}")
    public JsonResponse getById(@PathVariable Integer id) {
        Article article = articleService.getById(id);
        if(article==null)
            return JsonResponse.paramError("查询失败");
        return JsonResponse.success("查询成功", article);
    }

    @GetMapping("/getSome")
    public JsonResponse findPage(@Nullable @RequestParam @Min(1) Integer pageNum,
                                 @Nullable @RequestParam @Min(1) Integer pageSize,
                                 @Nullable @RequestParam String title) {
        if(pageNum!=null&&pageSize!=null)
            pageNum = (pageNum - 1) * pageSize;
        else if(!(pageNum==null&&pageSize==null))
            return JsonResponse.paramError("参数错误");
        return JsonResponse.success("查询成功",articleService.get(pageNum, pageSize, title));
    }
}
